package com.wmx.service.impl;

import com.wmx.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

/**********************************
 * @author wmx
 * @date 2019/9/6 14:40
 * @description:
 * @version 1.0
 ************************************/
@Slf4j
@Service
public class IAsyncService implements AsyncService {
    public static Random random =new Random();
    @Async
    @Override
    public Future<String> doTaskOne(CountDownLatch countDownLatch) {
        try {
            log.info("开始执行任务一");
            long start = System.currentTimeMillis();
            Thread.sleep(random.nextInt(20000));
            long end = System.currentTimeMillis();
            log.info("完成任务一，耗时：" + (end - start) + "毫秒");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            countDownLatch.countDown();
        }
        return new AsyncResult<>("任务一完成");
    }
    @Async
    @Override
    public Future<String> doTaskTwo(CountDownLatch countDownLatch) {
        try {
            log.info("开始执行任务二");
            long start = System.currentTimeMillis();
            Thread.sleep(random.nextInt(10000));
            long end = System.currentTimeMillis();
            log.info("完成任务二，耗时：" + (end - start) + "毫秒");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            countDownLatch.countDown();
        }
        return new AsyncResult<>("任务二完成");
    }
    @Async
    @Override
    public Future<String> doTaskThree(CountDownLatch countDownLatch) {
        try {
            log.info("开始执行任务三");
            long start = System.currentTimeMillis();
            Thread.sleep(random.nextInt(10000));
            long end = System.currentTimeMillis();
            log.info("完成任务三，耗时：" + (end - start) + "毫秒");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            countDownLatch.countDown();
        }
        return new AsyncResult<>("任务三完成");
    }
}
